<template>
    <div>
        <div class="top_box container_box">
            <p class="page-title font-weight-500">课表管理
                <el-tooltip class="item"
                            effect="dark"
                            content="刷新"
                            placement="right">
                    <el-button class="refresh-btn"
                               icon="el-icon-refresh"
                               type="primary"
                               circle
                               plain
                               @click="getTableData"
                               size="mini"></el-button>
                </el-tooltip>
            </p>
            <!-- <el-tabs v-model="queryData.week">
                <el-tab-pane v-for="(item, index) in curriculumWeekList"
                             :key="item.name"
                             :label="item.name"
                             :name="item.name">
                </el-tab-pane>
            </el-tabs> -->
        </div>
        <div class="padding_box">
            <div class="search_box container_box">
                <!-- u-flex u-row-between -->
                <div class="">
                    <el-form :inline="true"
                             label-width="80px"
                             :model="queryData">
                        <el-form-item label="">
                            <el-cascader ref="myCascader"
                                         clearable
                                         filterable
                                         :show-all-levels="false"
                                         separator=">"
                                         placeholder="请选择课程类型"
                                         v-model="productCategory"
                                         :options="productCategoryList"
                                         :props="{ expandTrigger: 'hover', checkStrictly: true, value:'id',label:'name',children:'children', }">
                            </el-cascader>
                        </el-form-item>
                        <!-- <el-form-item>
                            <el-autocomplete clearable
                                             v-model="curriculumEle"
                                             popper-class="my-autocomplete"
                                             :debounce="500"
                                             :trigger-on-focus="false"
                                             :fetch-suggestions="(queryString, cb) => querySearchAsync1(queryString, cb,'search')"
                                             placeholder="请输入课程名搜索"
                                             @select="(item) => handleSelectCurriculumId(item,'search')">
                                <template slot-scope="{ item }">
                                    <div v-if="item.name"
                                         class="name">{{ item.categoryName }} {{ '（' + item.name + '）' }}</div>
                                    <div v-else
                                         class="name">无匹配数据</div>
                                </template>
                            </el-autocomplete>
                        </el-form-item> -->
                        <el-form-item prop="userName">
                            <el-select v-model="queryData.week"
                                       clearable
                                       placeholder="请选择周几">
                                <el-option v-for="item in curriculumWeekList"
                                           :key="item.id"
                                           :label="item.name"
                                           :value="item.name">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="userName">
                            <el-select v-model="queryData.childrenClass"
                                       clearable
                                       placeholder="请选择年级">
                                <el-option v-for="item in classList"
                                           :key="item.name"
                                           :label="item.name"
                                           :value="item.name">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="">
                            <el-input clearable
                                      v-model="queryData.productName"
                                      placeholder="请输入课程名"></el-input>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="right-box u-flex u-row-between">
                    <div>
                        <el-button icon="el-icon-download"
                                   @click="exportExcel">导出数据</el-button>
                    </div>
                    <div>
                        <el-button type="primary"
                                   @click="getTableData">搜索</el-button>
                        <el-button icon="el-icon-refresh-left"
                                   @click="cleanQueryData">清空筛选</el-button>
                    </div>

                </div>
            </div>
            <div class="container_box">
                <div class="order_title u-flex u-row-between">
                    <span>课程表</span>
                    <el-button type="primary"
                               @click="addCurriculumType2()">添加课程</el-button>
                </div>
                <el-divider></el-divider>
                <el-table class="my_table"
                          header-row-class-name="order_header"
                          v-loading="loading"
                          :data="tableData"
                          tooltip-effect="dark"
                          style="width: 100%">
                    <!-- @selection-change="handleSelectionChange" -->

                    <el-table-column prop="name"
                                     label="课程"
                                     align="center">
                        <template slot-scope="scope">
                            <curriculum-card :cardData="scope.row"></curriculum-card>
                        </template>
                    </el-table-column>
                    <el-table-column prop="userName"
                                     label="任课教师"
                                     align="center">
                    </el-table-column>
                    <!-- <el-table-column prop="childrenClasss"
                                     label="年级"
                                     align="center">
                    </el-table-column> -->
                    <el-table-column prop="stock"
                                     label="报名人数/开课人数"
                                     align="center">
                        <template slot-scope="scope">
                            {{ scope.row.stock - scope.row.residueStock }} / {{ scope.row.stock }}
                        </template>
                    </el-table-column>
                    <!-- <el-table-column prop="schoolAddress"
                                     label="上课地点"
                                     align="center">
                    </el-table-column>
                    <el-table-column prop="schoolTime"
                                     label="上/下课时间"
                                     align="center">

                    </el-table-column> -->
                    <el-table-column prop=""
                                     align="center"
                                     label="课程可购买起止日">
                        <template slot-scope="scope">
                            {{ scope.row.validTime }} ~ {{ scope.row.unvalidTime }}
                        </template>
                    </el-table-column>
                    <el-table-column prop=""
                                     align="center"
                                     label="课程起止日">
                        <template slot-scope="scope">
                            {{ scope.row.schoolStrat }} ~ {{ scope.row.schoolEnd }}
                        </template>
                    </el-table-column>

                    <!-- <el-table-column prop="addTime"
                                     align="center"
                                     label="创建时间">
                    </el-table-column> -->
                    <el-table-column label="操作"
                                     fixed="right"
                                     width="180"
                                     align="center">
                        <template slot-scope="scope">
                            <el-button size="mini"
                                       type="success"
                                       @click="editCurriculumType2(scope.row)">修改</el-button>
                            <!-- <el-button size="mini"
                                       type="warning"
                                       @click="deleteUser(scope.row.id, scope.$index,2)">删除</el-button> -->
                        </template>
                    </el-table-column>
                </el-table>
                <div class="pagination">
                    <el-pagination background
                                   layout="total, prev, pager, next,sizes, jumper"
                                   :current-page="queryData.pageIndex"
                                   :page-size="queryData.pageSize"
                                   :page-sizes="[5, 10, 20, 40]"
                                   :total="pageTotal"
                                   @size-change="handleSizeChange"
                                   @current-change="handleCurrentChange"></el-pagination>
                </div>
            </div>
        </div>
        <!-- 添加弹出框 -->
        <el-dialog :title="currentEditEle.id ? `修改课程`:`添加课程`"
                   :visible.sync="showCurriculumTypeDialog"
                   width="50%">
            <el-form :model="currentEditEle"
                     :rules="rules"
                     label-width="150px">
                <el-form-item label="选择课程"
                              class="aa">
                    <el-autocomplete clearable
                                     v-model="curriculumEle"
                                     popper-class="my-autocomplete"
                                     :debounce="500"
                                     :trigger-on-focus="false"
                                     :fetch-suggestions="(queryString, cb) => querySearchAsync1(queryString, cb,'edit')"
                                     placeholder="请输入课程名搜索"
                                     @select="(item) => handleSelectCurriculumId(item,'edit')">
                        <template slot-scope="{ item }">
                            <div v-if="item.name"
                                 class="name">{{ item.categoryName }} {{ '（' + item.name + '）' }}</div>
                            <div v-else
                                 class="name">无匹配数据</div>
                        </template>
                    </el-autocomplete>
                </el-form-item>
                <el-form-item label="选择任课教师">
                    <el-autocomplete clearable
                                     v-model="teacherEle"
                                     popper-class="my-autocomplete"
                                     :debounce="500"
                                     :trigger-on-focus="false"
                                     :fetch-suggestions="querySearchAsync2"
                                     placeholder="请输入教师姓名或手机号搜索"
                                     @select="handleSelectTeacherId">
                        <template slot-scope="{ item }">
                            <div v-if="item.realName"
                                 class="name">{{ item.realName }} {{ '（' + item.telNo + '）' }}</div>
                            <div v-else
                                 class="name">无匹配数据</div>
                        </template>
                    </el-autocomplete>
                </el-form-item>
                <el-form-item label="选择年级">
                    <el-select v-model="currentEditEle.childrenClasss"
                               multiple
                               @change="testChange"
                               placeholder="请选择年级">
                        <el-option v-for="(item, index) in gradeList"
                                   :key="item.name"
                                   :label="item.name"
                                   :value="item.name"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="周几上课"
                              style="width:60%"
                              prop="weekStr">
                    <div class="u-flex">
                        <el-select style="margin-right:15px;"
                                   v-model="currentEditEle.weekStr"
                                   multiple
                                   :multiple-limit="2"
                                   @change="testChange"
                                   placeholder="请选择周几">
                            <el-option v-for="(item, index) in curriculumWeekList"
                                       :key="item.name"
                                       :label="item.name"
                                       :value="item.name"></el-option>
                        </el-select>
                    </div>
                </el-form-item>
                <el-form-item label="上/下课时间"
                              style="width:60%">
                    <div class="u-flex">
                        <el-time-picker is-range
                                        v-model="schoolTime2"
                                        range-separator=" ~ "
                                        start-placeholder="开始时间"
                                        end-placeholder="结束时间"
                                        placeholder="选择时间范围"
                                        value-format="HH:mm"
                                        @change="selectSchoolTime2">
                        </el-time-picker>
                        <el-time-picker style="margin-left:15px;"
                                        is-range
                                        v-model="schoolTime1"
                                        range-separator=" ~ "
                                        start-placeholder="开始时间"
                                        end-placeholder="结束时间"
                                        placeholder="选择时间范围"
                                        value-format="HH:mm"
                                        @change="selectSchoolTime1">
                        </el-time-picker>
                    </div>
                </el-form-item>
                <el-form-item label="上课地点"
                              style="width:60%">
                    <el-input type="text"
                              v-model="currentEditEle.schoolAddress"></el-input>
                </el-form-item>
                <!-- residueStock -->
                <el-form-item label="最大开课人数"
                              style="width:60%">
                    <el-input type="text"
                              v-model="currentEditEle.stock"></el-input>
                </el-form-item>
                <!-- schoolStrat，schoolEnd -->
                <el-form-item label="课程起止日">
                    <el-date-picker v-model="beginEndTime"
                                    type="datetimerange"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    value-format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                </el-form-item>
                <!-- validTime，unvalidTime -->
                <el-form-item label="课程可购买起止日">
                    <el-date-picker v-model="validTime"
                                    type="datetimerange"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    value-format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <span slot="footer"
                  class="dialog-footer">
                <el-button @click="showCurriculumTypeDialog = false">取 消</el-button>
                <!-- v-preventClick 防抖 -->
                <el-button type="primary"
                           @click="addOrEditCurriculum">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import axios from '@/utils/axios.js';
import businessCard from '@/components/business-card/business-card.vue'
import curriculumCard from '@/components/curriculum-card/curriculum-card.vue'
import { exportExcel } from '@/utils/exportExcel.js'
export default {
    name: 'basetable',
    components: {
        businessCard, curriculumCard
    },
    data() {
        return {
            pageTotal: 0,
            loading: false,
            tableData: [],
            queryData: {
                week: '',
                productName: '',
                pageNum: 1,
                pageSize: 10,
            },
            rules: {
                weekStr: [{ required: true, message: '请选择周几上课', trigger: 'blur' }],
            },
            classList: [
                { id: 1, name: '一年级', }, { id: 2, name: '二年级', }, { id: 3, name: '三年级', }, { id: 4, name: '四年级', },
                { id: 5, name: '五年级', }, { id: 6, name: '六年级', }, { id: 7, name: '初一', }, { id: 8, name: '初二', }, { id: 9, name: '初三', },
            ],
            // 课程分类
            curriculumWeekList: [
                { name: '周一' }, { name: '周二' }, { name: '周三' }, { name: '周四' }, { name: '周五' },
            ],
            gradeList: [
                { id: 1, name: '一年级', }, { id: 2, name: '二年级', }, { id: 3, name: '三年级', }, { id: 4, name: '四年级', },
                { id: 5, name: '五年级', }, { id: 6, name: '六年级', }, { id: 7, name: '初一', }, { id: 8, name: '初二', }, { id: 9, name: '初三', },
            ],
            schoolTime1: ['15:00:00', '19:00:00'],
            schoolTime2: ['15:00:00', '19:00:00'],
            beginEndTime: '',
            validTime: '',
            showCurriculumTypeDialog: false,
            currentEditEle: {
                id: null,
                icon: "test",
                schoolTimeStr: ['', ''],
                productUnit: '个',
            },
            editCurriculumTypeStatus: false,
            curriculumEle: '',
            teacherEle: '',
            // 课程分类回显idList
            productCategory: '',
            productCategoryList: [],
        };
    },
    watch: {
        productCategory(newV) {
            this.queryData.categoryId = newV[newV.length - 1]
            console.log('.>>>>>>>>>>>>>>>>>>>>>>>>>', this.queryData.categoryId)
        },
        'queryData.week': {
            handler(newV) {
                console.log(">>>>>>>>>>>>>>>>>>>>>>newV", newV)
                this.queryData.week = newV
                this.getTableData()
            }
        },
        curriculumEle(newV) {
            if (newV.length == 0) {
                this.currentEditEle.productId = ''
                this.currentEditEle.categoryId = ''
                this.currentEditEle.categoryName = ''
            }
        },
        teacherEle(newV) {
            if (newV.length == 0) {
                this.currentEditEle.userId = ''
                this.currentEditEle.userIcon = ''
                this.currentEditEle.telNo = ''
                this.currentEditEle.userName = ''
            }
        },
        beginEndTime(newV, oldValue) {
            if (newV && newV.length > 0) {
                //  + ' 00:00:00' + ' 23:59:59'
                this.currentEditEle.schoolStrat = newV[0]
                this.currentEditEle.schoolEnd = newV[1]
            } else {
                delete this.currentEditEle.schoolStrat
                delete this.currentEditEle.schoolEnd
            }

        },
        validTime(newV, oldValue) {
            if (newV && newV.length > 0) {
                //+ ' 00:00:00'+ ' 23:59:59'
                this.currentEditEle.validTime = newV[0]
                this.currentEditEle.unvalidTime = newV[1]
            } else {
                delete this.currentEditEle.validTime
                delete this.currentEditEle.unvalidTime
            }

        },
    },
    filters: {

    },
    created() {
        this.getTableData()
        this.getProductCategory()
        // this.getTableData();
    },
    methods: {
        // 获取所有课程分类
        getProductCategory() {
            axios({
                url: "admin/productCategory/tree",
                method: "post",
            }).then(result => {
                const { data } = result;
                data.forEach(ele => {
                    this.removeChildren(ele)
                });
                this.productCategoryList = data || [];
            })
        },
        removeChildren(node) {
            if (!node.children || !node.children.length) {
                delete node.children
            }
            if (node.children && node.children.length) {
                for (let i = 0; i < node.children.length; i++) {
                    this.removeChildren(node.children[i])
                }
            }
            return true
        },
        cleanQueryData() {
            this.queryData = {}
        },
        exportExcel() {
            let data = Object.assign({}, this.queryData)
            let userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
            console.log('--------------------userInfo', userInfo)
            data.schoolId = userInfo.schoolId
            exportExcel(data, '课表数据Excel', 'admin/excel/schoolClassScheduleToExcel')
        },
        testChange(ee) {
            console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', ee)
        },
        getTableData() {
            var _this = this;
            this.loading = true
            axios({
                url: "/admin/classSchedule/listPageByClass",
                method: "post",
                data: this.queryData,
            }).then(res => {
                if (res.code == 0) {
                    _this.tableData = res.data.list;
                    _this.pageTotal = res.data.total;
                }
                this.loading = false;
            }).catch(err => {
                this.loading = false;
            })
        },
        exportSchoolClassSchedule() {
            axios({
                url: "/ admin/excel/schoolClassScheduleToExcel",
                method: "post",
                data: this.queryData,
            }).then(res => {
                if (res.code == 0) {

                }
                this.loading = false;
            }).catch(err => {
                this.loading = false;
            })
        },

        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.queryData.pageSize = val
            this.getTableData()
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.queryData.pageNum = val
            this.getTableData()
        },
        // 详情
        goDetails(row) {
            this.$router.push({ path: '/curriculumDetails', query: { id: row.id } });
        },
        // 添加
        addCurriculumType2() {
            this.schoolTime1 = ['15:00:00', '19:00:00']
            this.schoolTime2 = ['15:00:00', '19:00:00']
            this.beginEndTime = ''
            this.validTime = ''
            this.teacherEle = ''
            this.curriculumEle = ''
            this.currentEditEle.id = null
            this.currentEditEle.icon = '*'
            this.currentEditEle.schoolTimeStr = ['', ''],
                this.showCurriculumTypeDialog = true
        },
        // 编辑
        editCurriculumType2(item) {
            this.showCurriculumTypeDialog = true
            this.currentEditEle = Object.assign({}, item)
            this.teacherEle = this.currentEditEle.userName + '(' + this.currentEditEle.telNo + ')'
            this.curriculumEle = this.currentEditEle.categoryName + '(' + this.currentEditEle.productResp.name + ')'
            let schoolTimeStr = this.currentEditEle.schoolTimeStr
            let arr = schoolTimeStr[0].split(' ~ ')
            let arr2 = schoolTimeStr[1].split(' ~ ')
            arr[0] = arr[0] + ':00'
            arr[1] = arr[1] + ':00'
            arr2[0] = arr2[0] + ':00'
            arr2[1] = arr2[1] + ':00'
            this.schoolTime1 = arr
            this.schoolTime2 = arr2
            this.beginEndTime = [this.currentEditEle.schoolStrat, this.currentEditEle.schoolEnd]
            this.validTime = [this.currentEditEle.validTime, this.currentEditEle.unvalidTime]
            console.log('>>>>>>>>>>>>>>>>>>>>>', item)
        },

        // 删除用户
        deleteUser(id, index, type) {
            // 二次确认删除
            this.$confirm('课程删除后将不可恢复请谨慎操作，确定删除？ (课程删除后不影响已发生的订单和交易数据)',
                '删除课程',
                {
                    type: 'warning'
                })
                .then(() => {
                    let data = { "id": id }
                    axios({
                        url: "/admin/classSchedule/delete",
                        method: "post",
                        data
                    }).then(result => {
                        if (result.code == 0) {
                            this.tableData.splice(index, 1);
                            this.$message.success(result.errMsg || '删除成功')
                            this.getTableData();
                        } else {
                            this.$message.error(result.errMsg || '删除失败')
                        }
                    })
                })
                .catch(() => { });
        },
        querySearchAsync1(queryString, cb, type) {
            if (queryString.length > 0) {
                let data = {
                    keyword: queryString
                }
                axios({
                    url: "/admin/product/listPage",
                    method: "post",
                    data
                }).then(res => {
                    let arr = []
                    if (res.code == 0 && res.data.list) {
                        if (res.data.list && res.data.list.length > 0) {
                            res.data.list.forEach(ele => {
                                arr.push({
                                    id: ele.id,
                                    categoryId: ele.categoryId,
                                    categoryName: ele.categoryName,
                                    name: ele.name,
                                    pic: ele.pic,
                                    value: ele.categoryName + '(' + ele.name + ')'
                                })
                            });
                            cb(arr);
                        } else {
                            let arr = [{ value: '无匹配数据' }]
                            cb(arr);
                        }
                    }
                })
            }
        },
        // 点击查询数据
        handleSelectCurriculumId(item, type) {
            if (type == 'edit') {
                this.currentEditEle.productId = item.id
                this.currentEditEle.productName = item.name
                this.currentEditEle.categoryId = item.categoryId
                this.currentEditEle.categoryName = item.categoryName
            } else if (type == 'search') {
                this.queryData.productName = item.name
            }
        },
        querySearchAsync2(queryString, cb) {
            if (queryString.length > 0) {
                let data = {
                    keyword: queryString,
                    type: 1,
                }
                axios({
                    url: "/admin/user/listPage",
                    method: "post",
                    data
                }).then(res => {
                    let arr = []
                    if (res.code == 0 && res.data.list) {
                        if (res.data.list && res.data.list.length > 0) {
                            res.data.list.forEach(ele => {
                                arr.push({
                                    id: ele.id,
                                    realName: ele.realName,
                                    telNo: ele.telNo,
                                    icon: ele.icon,
                                    value: ele.realName + '(' + ele.telNo + ')'
                                })
                            });
                            cb(arr);
                        } else {
                            let arr = [{ value: '无匹配数据' }]
                            cb(arr);
                        }
                    }
                })
            }
        },
        // 点击查询数据
        handleSelectTeacherId(item) {
            this.currentEditEle.userId = item.id
            this.currentEditEle.userIcon = item.icon
            this.currentEditEle.telNo = item.telNo
            this.currentEditEle.userName = item.realName
        },
        selectSchoolTime1(newV) {
            console.log('>>>>>>>>>>>>>>>>>>>>schoolTime1', newV[0] + ' ~ ' + newV[1])
            if (newV && newV.length > 0) {
                this.currentEditEle.schoolTimeStr[0] = newV[0] + ' ~ ' + newV[1]
            } else {
                this.currentEditEle.schoolTimeStr[0] = ''
            }
        },
        selectSchoolTime2(newV) {
            console.log('>>>>>>>>>>>>>>>>>>>>schoolTime2', newV[0] + ' ~ ' + newV[1])
            if (newV && newV.length > 0) {
                this.currentEditEle.schoolTimeStr[1] = newV[0] + ' ~ ' + newV[1]
            } else {
                this.currentEditEle.schoolTimeStr[1] = ''
            }
        },
        addOrEditCurriculum() {
            let tipText = '添加'
            if (this.currentEditEle.id) {
                tipText = '修改'
            }
            // this.currentEditEle.residueStock = this.currentEditEle.stock
            if (this.currentEditEle.userId == 0) {
                this.currentEditEle.userId = ''
            }
            console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>', this.currentEditEle)
            axios({
                url: "/admin/classSchedule/save",
                method: "POST",
                data: this.currentEditEle,
            }).then(result => {
                if (result.code == 0) {
                    this.$message.success(result.errMsg || `${tipText}成功`)
                    this.showCurriculumTypeDialog = false
                    this.getTableData()
                } else {
                    this.$message.error(result.errMsg || `${tipText}失败`)
                }
            })
        },
    }
};
</script>

<style lang="scss" scoped >
.top_box {
    background-color: #fff;
    padding-bottom: 0;
    ::v-deep {
        .el-tabs__header {
            margin: 0 !important;
        }
        .el-tabs__item {
            color: #999;
            &.is-active {
                color: #1b93f8;
            }
        }
    }
}
.good_more_info {
    position: relative;
    .order_item_box {
        padding: 15px 0;
        .order_img {
            border-radius: 8px;
            width: 72px;
            height: 72px;
            margin-right: 8px;
        }
        .order_title1 {
            font-size: 14px;
            color: #333;
            margin-bottom: 5px;
        }
        .order_guige {
            margin-top: 10px;
            font-size: 12px;
            color: #999;
        }
    }
}
.aa {
    ::v-deep {
        .el-input {
            width: 450px;
        }
    }
}
</style>
<style lang="scss">
</style>
